
# 1 读取数据
# from temp.入参接口 import 图纸入参接口
from temp.入参接口3 import 图纸入参接口
draw_info = 图纸入参接口
print(draw_info)


# 2. 数据格式适配器（兼容新旧接口格式）
from utils.fun1 import convert_drawing_format
draw_info = draw_info['user_drawing_info']
draw_info = convert_drawing_format(draw_info)
print(f"🔄 数据格式转换完成，转换后数据条数: {len(draw_info) if isinstance(draw_info, list) else 1}")

# 2 修补数据
from utils.fun1 import fix_drawing_surfaces
df_data = fix_drawing_surfaces(draw_info)
print(len(df_data))
# print(df_data)



# 3 主流程
import os
from dotenv import load_dotenv
load_dotenv()

NEO4J_URI = os.getenv("NEO4J_URI")
NEO4J_USER = os.getenv("NEO4J_USER")
NEO4J_PASSWORD = os.getenv("NEO4J_PASSWORD")
NEO4J_AUTH = (NEO4J_USER, NEO4J_PASSWORD)

from 正向分解2 import SmartProcessDesigner
planer = SmartProcessDesigner(NEO4J_URI, NEO4J_AUTH)
planer.read_final_inspection(df_data)
planer.run()
result= planer.new_graph['标准工序工步']

print()


# 4. 数据格式适配器（兼容新旧接口格式） 在这里写操作 不调包
import json

# 初始化转换后的操作列表
converted_all_operations = []

# 默认的设备资源信息
DEFAULT_CHILDREN = [
    {
        "number": "pRCD00165",
        "name": "主动轮转速",
        "type": "ParamIteration",
        "modelDefinition": "Param",
        "defaultValue": "245",
        "unit": "r/min"
    },
    {
        "number": "pEQP00136",
        "name": "球面铣磨机",
        "type": "ResourceIteration",
        "modelDefinition": "Equipment",
        "quantity": "1",
        "unit": "台"
    }
]

for process_id, process_info in result.items():
    # 新建一个空字典，用于存储转换后的工序信息
    converted_one_operation = {}
    
    # 设置必须的字段
    converted_one_operation['number'] = "SP00029"  # 写死的固定值
    
    # 从process_info中获取工序名称
    if '工序节点' in process_info and 'properties' in process_info['工序节点']:
        converted_one_operation['name'] = process_info['工序节点']['properties'].get('工序名称', '未知工序')
    else:
        converted_one_operation['name'] = '未知工序'
    
    # 设置默认的固定值
    converted_one_operation['type'] = "OperationIteration"
    converted_one_operation['modelDefinition'] = "MachiningOperation"
    
    # 初始化children列表
    converted_one_operation['children'] = []
    
    # 添加工步信息（从工步列表中获取）
    if '工步列表' in process_info:
        for step_idx, step_info in enumerate(process_info['工步列表'], 1):
            if '工步节点' in step_info and 'properties' in step_info['工步节点']:
                step_properties = step_info['工步节点']['properties']
                step_data = {
                    "number": f"BR{str(4 + step_idx).zfill(7)}",  # 生成工步编号，从BR0000004开始
                    "name": step_properties.get('工步名称', f'工步{step_idx}'),
                    "type": "Sequence",
                    "modelDefinition": "Sequence",
                    "description": step_properties.get('工步内容及加工要求', ''),
                    "children": DEFAULT_CHILDREN.copy()
                }
                
                # 添加工步检列表作为inspectionInfoItems
                if '工步检列表' in step_info:
                    step_data['inspectionInfoItems'] = []
                    for inspect_idx, inspect_info in enumerate(step_info['工步检列表'], 1):
                        if 'properties' in inspect_info:
                            inspect_properties = inspect_info['properties']
                            inspect_item = {
                                "orderNo": inspect_idx,
                                "name": inspect_properties.get('检验项目名称', f'检验项{inspect_idx}'),
                                "checkClass": inspect_properties.get('分类名称', '未知分类'),
                                "unit": inspect_properties.get('计量单位', ''),
                                "checkFace": inspect_properties.get('检测面', ''),
                                "technicalIndex": inspect_properties.get('设计值技术指标', ''),
                                "type": "InspectionInfoItem",
                                "modelDefinition": "InspectionSequenceItem"
                            }
                            step_data['inspectionInfoItems'].append(inspect_item)
                
                converted_one_operation['children'].append(step_data)
    
    # 添加工序检列表作为inspectionInfoItems
    if '工序检列表' in process_info:
        converted_one_operation['inspectionInfoItems'] = []
        for inspect_idx, inspect_info in enumerate(process_info['工序检列表'], 1):
            if 'properties' in inspect_info:
                inspect_properties = inspect_info['properties']
                inspect_item = {
                    "orderNo": inspect_idx,
                    "name": inspect_properties.get('检验项目名称', f'工序检验项{inspect_idx}'),
                    "checkClass": inspect_properties.get('分类名称', '未知分类'),
                    "unit": "",  # 工序检中没有明确的单位字段
                    "checkFace": inspect_properties.get('检测面', ''),
                    "technicalIndex": inspect_properties.get('设计值技术指标', ''),
                    "type": "InspectionInfoItem",
                    "modelDefinition": "InspectionOperationItem"
                }
                converted_one_operation['inspectionInfoItems'].append(inspect_item)
    
    # 添加优化建议（固定文本）
    converted_one_operation['optimization_reason'] = "无！！！！！"
    
    # 将转换后的工序信息添加到列表中
    converted_all_operations.append(converted_one_operation)

# 创建最终的输出结构
final_output = {
    "operations": converted_all_operations
}

# 打印转换后的结果
print("\n转换后的工艺数据格式：")
print(json.dumps(final_output, ensure_ascii=False, indent=2))

# 保存转换后的结果到文件
output_file = "./out_kg/转换后的工艺推荐参数.json"
with open(output_file, 'w', encoding='utf-8') as f:
    json.dump(final_output, f, ensure_ascii=False, indent=2)

print(f"\n转换后的结果已保存到：{output_file}")
